package MySql;

import java.sql.*;

import static MySql.MysqlOperate.MySQL_Command;

public class MySqlStart {
    final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";//驱动
    public final static String DB_MYSQL = "WeChat";//默认要操作的数据库名称
    //mysql用户名
    final static String name = "root";//用户名
    //mysql密码
    final static String pwd = "123456";//密码
    //指定连接数据库的url
    final static String DB_URL = "jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
    final static String USER_DB_URL = "jdbc:mysql://127.0.0.1:3306/" + DB_MYSQL + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";

    //——————————————————————————————————————————————————————————————————————————————————————————————
    public final static String creatDB = "CREATE DATABASE IF NOT EXISTS "+DB_MYSQL+";";

    public final static String creatPerson="create table PERSON\n" +
            "(\n" +
            "QQ  VARCHAR(32) PRIMARY KEY comment 'QQ',\n" +
            "PASSWORD VARCHAR(32) comment '密码',\n" +
            "NAME VARCHAR(32) comment '昵称',\n" +
            "TEL VARCHAR(32) comment '电话',\n" +
            "SEX int comment '性别',\n" +
            "BIRTHDAY DATE comment '出生日期',\n" +
            "CREATDATE DATETIME comment '创建时间',\n" +
            "STATE int comment '状态'\n" +
            ")default CHARSET=utf8;";

    //——————————————————————————————————————————————————————————————————————————————————————————————
    private Connection conn=null;      //java.sql.Connection（连接）处理与特定数据库的连接
    private PreparedStatement ps=null; //java.sql.PreparedStatement （声明）在指定连接中处理SQL语句
    private ResultSet rs=null;         //java.sql.ResultSet（结果集） 处理数据库操作结果集
    //——————————————————————————————————————————————————————————————————————————————————————————————

    public Connection getConnection(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //java.sql.DriverManager 处理驱动程序的加载和建立新数据库连接
            conn= DriverManager.getConnection(DB_URL,name,pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void InitDatabaseCreate() throws SQLException {
        if (!IsExistDatabase(DB_MYSQL))
        {
            System.out.println("检测到数据库未创建，正在创建...");
            CreatDatabase();
            MySQL_Command(creatPerson);
        }
        else
        {
            System.out.println("检测到数据库已经创建了...");
        }
    }

    public static boolean IsExistDatabase(String DataBase_Name) {
        Connection conn = null;
        Statement stmt = null;
        boolean Exist = false;
        try {
            //注册jdbc驱动
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, name, pwd);
            String sql = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name=\"" + DataBase_Name + "\"";
            System.out.println("数据库操作：" + sql);
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs==null)
                return false;
            if (rs.next()&&rs.getInt(1) == 0) {
                Exist = false;
            } else {
                Exist = true;
            }
            stmt.close();
            conn.close();
            return Exist;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean CreatDatabase() {
        Connection conn = null;
        Statement stmt = null;
        try {
            //注册jdbc驱动
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, name, pwd);
            System.out.println("正在创建表......");
            stmt = conn.createStatement();
            //创建数据库
            stmt.execute(creatDB);
            System.out.println("数据库操作：" + creatDB);

            stmt.close();
            conn.close();
            System.out.println("\n##########创建数据库成功##########\n");
        } catch (Exception e) {
            System.out.println("\n##########创建表失败！##########\n");
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static void GreatDBTable(Statement stmt, String SQLCode) {
        try {
            if (stmt.execute(SQLCode)==true) {
                System.out.println("\n########成功创建基础表:########\n" + SQLCode.toString());
            } else {
                System.out.println("\n########创建表基础失败:########\n" + SQLCode.toString());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
